import React, { Component } from 'react'
import { ActivityIndicator, FlatList, View, Image, Text } from 'react-native'
import { Rating } from 'react-native-elements'
import { connect } from 'react-redux'
import CommentActions from '../Redux/CommentRedux'

// Styles
import styles from './Styles/CommentStyle'

class Comment extends Component {
  constructor (props) {
    super(props)
    this.state = {
      id: props.id
    }
  }

  componentDidMount() {
    this.props.commentRequest(this.state.id)
  }

  renderItem({item}) {
    return (
      <View style={styles.row}>
        <View style={styles.rowHeader}>
          <Image source={{uri:item.avatar}} style={styles.avatar} />
          <View style={{flex:1}}>
            <View style={{flex:1,flexDirection:'row'}}>
              <Text style={styles.name}>{item.name}</Text>
              <Rating
                type='star'
                readonly
                startingValue={Number(item.star)}
                imageSize={16}
                style={{marginRight:5}}
              />
              <View style={{flex:1,alignItems:'flex-end'}}>
                <Text>{item.date}</Text></View>
            </View>
            <Text style={{marginLeft:2}}>[{item.project}]</Text>
          </View>
        </View>
        <Text style={styles.content}>{item.content}</Text>
      </View>
    )
  }

  renderEmpty() {
    return (
      <View style={styles.empty}>
        <Text>暂无评价</Text>
      </View>
    )
  }

  keyExtractor = (item,index) => index

  render () {
    const data = []
    if(this.props.comment.fetching) {
      return <ActivityIndicator style={{marginTop:20}} />
    } else if(this.props.comment.error) {
      return <Text style={{marginTop:20,textAlign:'center'}}>出错了</Text>
    }
    return (
      <FlatList 
        data={this.props.comment.payload}
        renderItem={this.renderItem}
        keyExtractor={this.keyExtractor}
        ListEmptyComponent={this.renderEmpty}
      />
    )
  }
}

const mapStateToProps = (state) => {
  return {
    comment: state.comment,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    commentRequest: (id) => dispatch(CommentActions.commentRequest(id))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Comment)
